//
//  SYPickerView.m
//  ChatDemo-UI2.0
//
//  Created by zz on 17/2/17.
//  Copyright © 2017年 zz. All rights reserved.
//

#import "SYPickerView.h"

@interface SYPickerView()<UIPickerViewDataSource,UIPickerViewDelegate>




@end

@implementation SYPickerView{
    
    int nowYear;//当前年份
    int nowMonth; //当前月份
}

#pragma mark -Setter
- (void)setSourceArray:(NSMutableArray *)sourceArray{
    
    _sourceArray = sourceArray;
    
    [self.picker reloadAllComponents];
    
    if (_indexOfType > 0) {
        
        [self.picker selectRow:_indexOfType inComponent:0 animated:NO];
    }
    
    if (_indexOfDetailType > 0) {
        
        [self.picker selectRow:_indexOfDetailType inComponent:1 animated:NO];
    }

}

- (void)setDetailArray:(NSMutableArray *)detailArray{
    
    _detailArray = detailArray;
    [self.picker reloadAllComponents];
}

- (void)setIndexOfType:(NSInteger)indexOfType{
    
    _indexOfType = indexOfType;
    
//    if (_indexOfType != 0) {
//        
//        [self.picker selectRow:_indexOfType inComponent:0 animated:NO];
//        [self.picker selectRow:_indexOfDetailType inComponent:1 animated:NO];
//    }
}

- (void)setPickerMode:(SYPickerMode)pickerMode{
    
    _pickerMode = pickerMode;
    
    if (_pickerMode == SYPickerModeMonth) { //选择月份
        
        NSMutableArray *monthArr = [NSMutableArray arrayWithObjects:@"1月",@"2月",@"3月",@"4月",@"5月",@"6月",@"7月",@"8月",@"9月",@"10月",@"11月",@"12月", nil];
        self.detailArray = monthArr;

        NSMutableArray *yearArr = [NSMutableArray array];
        
        
        //获取当前年份
        NSDate *date = [NSDate date];
        
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        unsigned unitFlags = NSCalendarUnitYear |
        NSCalendarUnitMonth |  NSCalendarUnitDay |
        NSCalendarUnitHour |  NSCalendarUnitMinute |
        NSCalendarUnitSecond | NSCalendarUnitWeekday;
        
        NSDateComponents* comp = [gregorian components: unitFlags
                                              fromDate:date];
        
        nowYear = (int)comp.year;
        
        nowMonth = (int)comp.month;
        
        NSString *month = [NSString stringWithFormat:@"%ld月",[comp month]];
//        self.indexOfDetailType = [monthArr indexOfObject:month];
        _indexOfDetailType = [monthArr indexOfObject:month];
        [self.picker selectRow:_indexOfDetailType inComponent:1 animated:NO];
        
        int index = 0;
        
        for (int i = 1980; i < 1980 + 100; i ++ ) {
            
            if (nowYear == i) {
                
                index = nowYear - 1980;
            }
            
            NSString *yearStr = [NSString stringWithFormat:@"%d年",i];
            
            [yearArr addObject:yearStr];
        }
        
        self.sourceArray = yearArr;
        _indexOfType = index;
        [self.picker selectRow:_indexOfType inComponent:0 animated:NO];
    }
}

- (void)setIndexOfDetailType:(NSInteger)indexOfDetailType{
    
    _indexOfDetailType = indexOfDetailType;
    
//    if (_indexOfDetailType != 0) {
//        
//        [self.picker selectRow:_indexOfDetailType inComponent:1 animated:NO];
//        [self.picker selectRow:_indexOfType inComponent:0 animated:NO];
//    }
}


#pragma mark -LifeCycle
- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        self.frame = [UIScreen mainScreen].bounds;
        
        UIWindow *window = KeyWindow;
        [window addSubview:self];
        
        [self commonInit];
        
    }
    
    return self;
}

- (void)commonInit{
    
    _picker = [[UIPickerView alloc] init];
    _picker.delegate = self;
    _picker.dataSource = self;
    _picker.backgroundColor = [UIColor whiteColor];
    _picker.frame = CGRectMake(0, SCREENHEIGH - 170,self.width, 170);
    [self addSubview:_picker];
    
    _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(_picker.frame) - 35, SCREENWIDTH, 35)];
    _toolbar.userInteractionEnabled = YES;
    [_toolbar setBackgroundColor:[UIColor whiteColor]];
    /*ios11 下UIBarbuttonitem存在bug*/
//    _toolbar.backgroundColor = [UIColor clearColor];
//    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(tapAction)];
    
    UIBarButtonItem *btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [btn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    UIBarButtonItem *sureBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成   " style:UIBarButtonItemStyleDone target:self action:@selector(sureAction)];
    
//    UIBarButtonItem *sureBtn = [[UIBarButtonItem alloc] initWithCustomView:btn]
    ;
    [sureBtn setTitleTextAttributes:@{NSForegroundColorAttributeName:RGBACOLOR(57, 173, 255, 1)} forState:UIControlStateNormal];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,sureBtn,nil];
    [_toolbar setItems:buttonsArray];
    
    [self addSubview:_toolbar];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH-170-35)];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
//    [self addGestureRecognizer:tap];
    [bgView addGestureRecognizer:tap];
//
    [self addSubview:bgView];
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    

}

- (void)dealloc {
    
    NSLog(@"sypickerview释放");
}

#pragma mark -UIPickerViewDataSource && UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if (component == 0) {
        
//        return _sourceArray.count;
        

        return _sourceArray.count;

    }else{
        
        if (_pickerMode == SYPickerModeStudent) {
            
            NSArray *array = [[_sourceArray objectAtIndex:_indexOfType] objectForKey:@"item"];
            
            return array.count;
        }else{
            
            return _detailArray.count;
        }
        
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (_pickerMode == SYPickerModeStudent){
    
        if (component == 0) {
            
            return [[_sourceArray objectAtIndex:row] objectForKey:@"studentname"];
        }
        
        NSArray *arr = [[_sourceArray objectAtIndex:_indexOfType] objectForKey:@"item"];
        NSString *className=[[arr objectAtIndex:row] objectForKey:@"classname"];
        return className;
        
    }else{
        
        if (component == 0) {
            
            return [_sourceArray objectAtIndex:row];
        }
        
        if (!_detailArray || _detailArray.count <= 0) {
            
            TTAlert(@"请传给我月份数组");
            return 0;
            
            
        }
        
        return _detailArray[row];
    }
    

}



-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (component == 0) {//第一列省的选中改变后，就要更新第二列数据
        
        if (_pickerMode == SYPickerModeMonth) { //选择日期 判断如果大于当前年份,从新跳回当前年份
            
            int selYear = [_sourceArray[row] intValue];
            
            if (selYear > nowYear) {
                
                [pickerView selectRow:nowYear - 1980 inComponent:0 animated:YES];
                return;
            }
            
        }
        
        //更新选中省份的索引
        _indexOfType = row;
        
        
        //部份刷新
        [pickerView reloadComponent:1];
        
        //不管之前第二列选中第几行，重新刷新数据后，都显示每二列的第一行
        [pickerView selectRow:0 inComponent:1 animated:YES];
        self.indexOfDetailType = 0;

    }else
    {
        if (_pickerMode == SYPickerModeMonth) {
            
            int selYear = [_sourceArray[_indexOfType] intValue];
            if (selYear == nowYear && _pickerMode == SYPickerModeMonth) { //选择月份 判断如果在当前年份并且大于当前月份,从新跳回当前月份
                
                int monthSel = [_detailArray[row] intValue];
                
                if (monthSel > nowMonth) {
                    
                    [pickerView selectRow:nowMonth - 1 inComponent:1 animated:YES];
                    return;
                }
                
            }
        }
        
        self.indexOfDetailType = row;
    }
    
}


#pragma mark 设置宽度
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (component == 0) {
        return 80;
    }
    
    return 200;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel *pickerLabel = (UILabel *)view;
    
    if (!pickerLabel) {
        
        pickerLabel = [[UILabel alloc] init];
        
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

#pragma mark -Actions

- (void)tapAction{
    
//    [UIView animateWithDuration:1 animations:^{
//        
//        self.y += 200;
//        
//    } completion:^(BOOL finished) {
//       
//        self.hidden = YES;
//    }];
    
//    self.hidden = YES;
    [self removeFromSuperview];
}

- (void)sureAction{
    
    if (_sureBlock) { //回调block
        
        if (_pickerMode == SYPickerModeStudent) {
            
            _sureBlock(_sourceArray[_indexOfType],_indexOfType,_indexOfDetailType);
        }else{
            
            NSDictionary *dict = @{@"year":_sourceArray[_indexOfType],@"month":_detailArray[_indexOfDetailType]};
            _sureBlock(dict,_indexOfType,_indexOfDetailType);
        }
        
        [self removeFromSuperview];
    }
}

/**显示*/
- (void)show{
    
    self.hidden = NO;
    
//    [UIView animateWithDuration:1 animations:^{
//        
//        self.y -= 200;
//        
//    } completion:^(BOOL finished) {
//        
//        
//    }];
}

@end
